package ws;

import java.util.ArrayList; 
import java.util.Collection;
import org.orm.PersistentException;
import org.orm.PersistentTransaction;
import java.lang.reflect.Type;   

import orm.dao.ClienteDAO;
import orm.dao.LogDAO;

import orm.Cliente;
import orm.DAOFactory;
import orm.Log;
import safe.Encriptar;
import soapvo.LogSOAPVO;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class LogSOA {
 


	public static String ingresarLog(String json) throws PersistentException{

		//Se instancia un objeto de la clase Encriptar y se define la key.
		String key = "apretandoparapasarelramo";
        Encriptar obj = new Encriptar(key);
        
		Gson gson = new Gson();
		Type LogSOAPVOType = new TypeToken<LogSOAPVO>(){}.getType();
		LogSOAPVO log = gson.fromJson(json, LogSOAPVOType);
		
		System.out.println("A-deserializacion:     " + log);
			
		PersistentTransaction pt = orm.PinPassPersistentManager.instance().getSession().beginTransaction();
		
		try {
			orm.DAOFactory lDAOFactory = orm.DAOFactory.getDAOFactory();
			
			ClienteDAO lormClienteDAO = lDAOFactory.getClienteDAO();
			Cliente lormCliente = lormClienteDAO.loadClienteByORMID(1);
			
			LogDAO lormLogDAO =  lDAOFactory.getLogDAO();
			Log lormLog = lormLogDAO.createLog();
			lormLog.setLog_fecha(log.getFecha());
			lormLog.setLog_contador(log.getContador());
			lormLog.setLog_resultado(log.getResultado());	
			lormLog.setClientecli(lormCliente);
			lormLogDAO.save(lormLog);
			
			pt.commit();
		} 
		
		catch (Exception e) {
			pt.rollback();
		}
		return json;
	}
	
	
	public static String verLog() throws PersistentException {		
		
		//Se instancia un objeto de la clase Encriptar y se define la key.
		String key = "apretandoparapasarelramo";
		Encriptar obj = new Encriptar(key);
		
		DAOFactory lDAOFactory = DAOFactory.getDAOFactory();
		Collection<LogSOAPVO> coleccionLogSOAPVO = new ArrayList<LogSOAPVO>();
		
		System.out.println("A-:     ");
		
		//	LogDAO lormLogDAO = lDAOFactory.getLogDAO();
		//	Log[] lormLog = lormLogDAO.listLogByQuery(null, null);
		Log[] lormLog = lDAOFactory.getLogDAO().listLogByQuery(null, null);
		
		System.out.println("C-:     ");
		
		int length = lormLog.length;
		for (int i = 0; i < length; i++) {
			System.out.println(lormLog[i].getLog_id() + ", " + lormLog[i].getLog_fecha() + ", " + lormLog[i].getLog_resultado() + ", " + lormLog[i].getLog_contador());
			LogSOAPVO objeto = LogSOAPVO.crearLogSOAPVO(lormLog[i]);
			coleccionLogSOAPVO.add(objeto);
		}
		
		String json = null;
		
		Gson gson = new Gson();
		json = gson.toJson(coleccionLogSOAPVO);
		
		String encriptadoLog = obj.encriptar(json);
		
		return encriptadoLog;
	}
	
	
	public static void main(String args[]) throws PersistentException{
		
		String clave = verLog();
	//	String clave2 = ingresarLog(clave);
		System.out.println("F-verrr:    " + verLog());
	}
}
